import { ref } from 'vue';

let IDCache = -1;

const CreateID = () => {
    return IDCache--;
}

export const InitMapping = (ParamConfig, DefaultValue) => {
    const ParamMapping = ref({});
    const Value = {};

    const WacthEventMapping = {};
    const DictMapping = {};
    const ChangeOptionMapping = {};
    const RuleMapping = {};



    ParamConfig.forEach(element => {
        if (element.Rule) {
            RuleMapping[element.key] = element.Rule
        }

        if (element.Event && element.Event.Wacth) {
            WacthEventMapping[element.key] = element.Event.Wacth
        }

        if (element.Event && element.Event.ParamOption) {
            ChangeOptionMapping[element.key] = element.Event.ParamOption;
        }

        if (element.hasOwnProperty('Dict') && !Array.isArray(element.Dict)) {
            const DictValue = element.Dict.split(':');
            if (DictValue.length == 3) {
                const [Parentkey, Child, Default] = DictValue;
                if (!DictMapping[Parentkey]) DictMapping[Parentkey] = {};
                DictMapping[Parentkey][element.key] = {
                    key: Child,
                    default: Default
                }
            }
        }
        ParamMapping.value[element.key] = element;
        if (element.skipParam) {
            console.log(element);
        } else if (DefaultValue && DefaultValue.hasOwnProperty(element.key)) {
            Value[element.key] = DefaultValue[element.key]
        } else if (element.hasOwnProperty('MultiKeyDefault')) {
            for (let i = 0; i < element.MultiKeyDefault.length; i++) {
                const _Item = element.MultiKeyDefault[i];
                Value[_Item.ValueKey] = _Item.default
            }
        } else if (element.hasOwnProperty('default')) {
            Value[element.key] = element.default
        } else {
            switch ((element.type + '').toLowerCase()) {
                case 'string':
                    Value[element.key] = '';
                    break;
                case 'radio':
                    Value[element.key] = '';
                    break;
                case 'checkbox':
                    Value[element.key] = false;
                    break;
                case 'number':
                    Value[element.key] = 0;
                    break;
                case 'int':
                    Value[element.key] = 0;
                    break;
                case 'primary':
                    Value[element.key] = CreateID();
                    break;
                default:
                    Value[element.key] = null;
                    break;
            }
        }
    });

    return {
        ParamMapping,
        WacthEventMapping,
        ChangeOptionMapping,
        DictMapping,
        RuleMapping,
        // 合并默认值
        Value: ref({ ...DefaultValue, ...Value })
    }
};


